<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex justify-between h-3">
        <span>运营数据</span>
        <el-tag v-if="isSuperAdmin" type="primary">全平台</el-tag>
        <el-tag v-else type="primary">当前店铺</el-tag>
      </div>
    </template>
    <div class="flex flex-row flex-wrap justify-between gap-6">
      <div
        v-for="item in data"
        :key="item.name"
        class="h-20 flex flex-col cursor-pointer items-center justify-center gap-2"
        @click="handleClick(item.routerName)"
      >
        <CountTo
          :prefix="item.prefix"
          :end-val="Number(item.value)"
          :decimals="0"
          class="text-3xl"
        />
        <span class="text-center">{{ item.name }}</span>
      </div>
    </div>
  </el-card>
</template>
<script lang="ts" setup>
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as TradeStatisticsApi from '@/api/mall/trade/statistics'
import { checkRole } from '@/utils/permission'

/** 运营数据卡片 */
defineOptions({ name: 'OperationDataCard' })

const isSuperAdmin = computed(() => checkRole(['super_admin', 'platform_admin', 'tenant_admin']))

const router = useRouter() // 路由

/** 数据 */
const data = reactive<any>({
  orderUndelivered: { name: '待发货', value: 9, routerName: 'TradeOrder' },
  orderAfterSaleApply: { name: '退款中', value: 4, routerName: 'TradeAfterSale' },
  orderWaitePickUp: { name: '待核销', value: 0, routerName: 'TradeOrder' },
  productAlertStock: { name: '库存预警', value: 0, routerName: 'ProductSpu' },
  productForSale: { name: '上架产品', value: 0, routerName: 'ProductSpu' },
  productInWarehouse: { name: '仓库产品', value: 0, routerName: 'ProductSpu' }
})

/** 查询订单数据 */
const getOrderData = async () => {
  const orderCount = await TradeStatisticsApi.getOrderCount()
  if (orderCount.undelivered != null) {
    data.orderUndelivered.value = orderCount.undelivered
  }
  if (orderCount.afterSaleApply != null) {
    data.orderAfterSaleApply.value = orderCount.afterSaleApply
  }
  if (orderCount.pickUp != null) {
    data.orderWaitePickUp.value = orderCount.pickUp
  }
}

/** 查询产品数据 */
const getProductData = async () => {
  const productCount = await ProductSpuApi.getTabsCount()
  data.productForSale.value = productCount['FOR_SALE']
  data.productInWarehouse.value = productCount['IN_WAREHOUSE']
  data.productAlertStock.value = productCount['ALERT_STOCK']
}

/**
 * 跳转到对应页面
 *
 * @param routerName 路由页面组件的名称
 */
const handleClick = (routerName: string) => {
  router.push({ name: routerName })
}

/** 初始化 **/
onMounted(() => {
  getOrderData()
  getProductData()
})
</script>
